package com.tech.http;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class HttpClientFactory {
	private static final Logger LOG = LoggerFactory
			.getLogger(HttpClientFactory.class);

	private DefaultHttpClient httpClient;

	private int timeout = 10;

	private int poolSize = 10;

	private PoolingClientConnectionManager clientConnManager;

	public void init() {
		long startTime = System.currentTimeMillis();
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
				.getSocketFactory()));
		clientConnManager = new PoolingClientConnectionManager(schemeRegistry,
				timeout, TimeUnit.SECONDS);
		clientConnManager.setDefaultMaxPerRoute(poolSize);
		clientConnManager.setMaxTotal(poolSize);
		httpClient = new DefaultHttpClient(clientConnManager, getHttpParams());
		LOG.info("Factory initialized already. cost: {}ms.",
				System.currentTimeMillis() - startTime);
	}

	public void destroy() {
		LOG.info("HttpClientFactory shutdown");
		long start = System.nanoTime();
		if (clientConnManager != null)
			clientConnManager.shutdown();
		LOG.info("[HttpClientFactory] close in {}ms",
				(System.nanoTime() - start) / 1000000);
	}

	private HttpParams getHttpParams() {
		HttpParams params = new BasicHttpParams();
		params.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "gbk");
		params.setParameter(CoreProtocolPNames.USER_AGENT, "rum/micah");
		params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout * 1000);
		params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
				timeout * 1000);
		return params;
	}

	public HttpClient get() {
		return httpClient;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public void setPoolSize(int poolSize) {
		this.poolSize = poolSize;
	}

}
